package cc.wsyw126.java.nowcoder.sword_offer;

import cc.wsyw126.java.lintCode.swap_two_nodes_in_linked_list.ListNode;

/**
 * Created by Administrator on 2017/4/14.
 * 输入两个链表，找出它们的第一个公共结点。
 */
public class FindFirstCommonNode {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        int list1Length= 0 ,list2Length =  0;
        ListNode pHead11 = pHead1;
        ListNode pHead21 = pHead2;
        while (pHead11!=null) {
            pHead11=pHead11.next;
            list1Length++;
        }
        while (pHead21!=null) {
            pHead21=pHead21.next;
            list2Length++;
        }
        pHead11=pHead1;
        pHead21=pHead2;
        int diff = list1Length - list2Length;
        if (diff>0) {
            while (diff-->0) {
                pHead11 = pHead11.next;
            }
        } else if (diff <0 ){
            while (diff++<0) {
                pHead21 = pHead21.next;
            }
        }
        while (pHead11!=null&&pHead21!=null) {
            if (pHead11.val == pHead21.val ) {
                return pHead11;
            }
            pHead11=pHead11.next;
            pHead21=pHead21.next;
        }
        return null;
    }
}
